package com.bawei.solr;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
/**
 * facet 统计代码演示
 */
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.QueryResponse;

/**
 * 统计查询
 * @author liang
 *D:\apache-tomcat-7.0.68_solr\bin
 */
public class FacetTest {

	public static void main(String[] args) throws SolrServerException {

		String solrUrl = "http://localhost:28080/solr/mycore2";

		HttpSolrClient solrServer = new HttpSolrClient(solrUrl);

		SolrQuery query = new SolrQuery();
		query.setQuery("*:*");
		query.setFacet(true);// 设置facet=on

//		query.addFacetField("age");// 设置需要facet的字段
		 query.add("facet.field", "age", "height");
		 query.add("facet.query", "age:[20 TO 30]");

//		 query.setParam("facet.prefix", "2"); // 表示Facet字段前缀，必须是某值打头

		query.setParam("facet.offset", "0"); // 开始条数,偏移量,它与facet.limit配合使用可以达到分页的效果
		query.setFacetLimit(10);// 限制facet返回的数量
		
		query.setFacetMinCount(1);// 设置返回的数据中每个分组的数据最小值，比如设置为1，则统计数量最小为1，不然不显示
		query.setFacetMissing(false);// 不统计null的值

		System.out.println(query.toString());

		QueryResponse response = solrServer.query(query);

//		response.getResults();
		List<FacetField> facets = response.getFacetFields();// 返回的facet列表
		for (FacetField facet : facets) {
			// 获取分组字段FacetField
			System.out.println(facet.getName());
			System.out.println("----------------");
			List<FacetField.Count> counts = facet.getValues();
			for (FacetField.Count count : counts) {

				System.out.println(count.getName() + ":" + count.getCount());
			}
			System.out.println();
		}
		
		System.out.println("获取FacetQuery的结果集");
		Map<String, Integer> facetQuery = response.getFacetQuery();
		Iterator<String> iterator = facetQuery.keySet().iterator();
		while(iterator.hasNext()){
			String next = iterator.next();
			System.out.println(next+":"+facetQuery.get(next));
		}

	}
}
